﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ChartControl.cs" company="">
//   
// </copyright>
// <summary>
//   The chart control.
// </summary>
// --------------------------------------------------------------------------------------------------------------------


using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using Systemathics.FrameWork;
using Systemathics.UserControls.Chart;
using Systemathics.UserControls.Chart.Properties;
using Series = System.Windows.Forms.DataVisualization.Charting.Series;

namespace Systemathics.UserControls
{

    [ToolboxBitmap(typeof (ChartControl), "UserControlsIcon.bmp")]
    public sealed partial class ChartControl : UserControl
    {
        private const double AXIS_LENGTH = 0.3; //1/3 of an hour 
        private readonly Dictionary<Guid, Series> CustomValuesSeries1;
        private readonly Dictionary<Guid, Series> CustomValuesSeries2;
        private readonly Dictionary<Guid, string> Names;
        private readonly GraphDelegate pAddGraph, pUpdateGraph, pAddGraphHystory ;
        private readonly Dictionary<Guid, Series> PLSeries;
        private readonly Dictionary<Guid, Series> PositionsSeries;
        private readonly Dictionary<Guid, Series> TradeOrBarSeries;
        private Series HistoricalSerie;
        private Guid SelectedGuid;
        private delegate void GraphDelegate(GraphEventArgs g);
        private RemotingGraphServer remoteGraphServer;
        private String Title;

        public ChartControl()
        {
            InitializeComponent();
            Dock = DockStyle.Fill;
            DoubleBuffered = true;

            Names = new Dictionary<Guid, string>();
            TradeOrBarSeries = new Dictionary<Guid, Series>();
            PLSeries = new Dictionary<Guid, Series>();
            PositionsSeries = new Dictionary<Guid, Series>();
            CustomValuesSeries1 = new Dictionary<Guid, Series>();
            CustomValuesSeries2 = new Dictionary<Guid, Series>();

            pUpdateGraph = new GraphDelegate(UpdateGraph);
            pAddGraph = new GraphDelegate(AddGraph);
            pAddGraphHystory = new GraphDelegate(AddGraphHystory);

            ChartInit();
            chart.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Minutes;
            InstrumentsComboBox.DroppedDown = true;
            ConnectToolStripButton.CheckStateChanged += ConnectToolStripButtonCheckStateChanged;
        }

        private void ConnectToolStripButtonCheckStateChanged(object sender, EventArgs e)
        {
            if (IsHandleCreated)
            {
                var bt = sender as ToolStripButton;
                if (bt.CheckState == CheckState.Checked)
                {
                    var form = new StrategyForm();
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        SelectedStrategy = form.Id;
                        Title = form.Name + " - " + form.Pattern + " Info: " + form.Info + " - Ver: " + form.Version + " - Created: " + form.CreationDate;
                    }
                    if(remoteGraphServer.isListenning)
                    {
                        ConnectToolStripButton.CheckState = CheckState.Indeterminate;
                        ConnectToolStripButton.Image = Resources.quick_restart;
                    }
                    else
                        ConnectToolStripButton.CheckState = CheckState.Unchecked;
                }
                else if (bt.CheckState == CheckState.Unchecked)
                {
                    Names.Clear();
                    TradeOrBarSeries.Clear();
                    PLSeries.Clear();
                    PositionsSeries.Clear();
                    CustomValuesSeries1.Clear();
                    CustomValuesSeries2.Clear();
                    InstrumentsComboBox.Items.Clear();
                    chart.Series.Clear();
                    ConnectToolStripButton.Checked = false;
                    ConnectToolStripButton.Image = Resources.exit;
                }
            }
        }
        private void ChartInit()
        {
            chart.Legends.Clear();
            chart.ChartAreas[0].Position.Auto = false;
            chart.ChartAreas[0].Position.X = 1;
            chart.ChartAreas[0].Position.Y = 1;
            chart.ChartAreas[0].Position.Width = 90;
            chart.ChartAreas[0].Position.Height = 90;

            chart.ChartAreas[0].AxisX.IsStartedFromZero = false;
            chart.ChartAreas[0].AxisX.IsLabelAutoFit = true;
            chart.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.WhiteSmoke;
            chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
            chart.ChartAreas[0].AxisX.ScrollBar.IsPositionedInside = true;
            chart.ChartAreas[0].AxisX.ScrollBar.Size = 15;

            chart.ChartAreas[0].AxisY.IntervalAutoMode = IntervalAutoMode.FixedCount;
            chart.ChartAreas[0].AxisY.LabelAutoFitMinFontSize = 10;
            chart.ChartAreas[0].AxisY.IsStartedFromZero = false;
            chart.ChartAreas[0].AxisY.IsLabelAutoFit = true;
            chart.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.WhiteSmoke;
            chart.ChartAreas[0].AxisY.ScaleView.Zoomable = true;

            chart.ChartAreas[0].AxisY2.IntervalAutoMode = IntervalAutoMode.FixedCount;
            chart.ChartAreas[0].AxisY2.LabelAutoFitMinFontSize = 10;
            chart.ChartAreas[0].AxisY2.IsStartedFromZero = false;
            chart.ChartAreas[0].AxisY2.IsLabelAutoFit = true;
            chart.ChartAreas[0].AxisY2.MajorGrid.LineColor = Color.WhiteSmoke;
            chart.ChartAreas[0].AxisY2.MinorGrid.LineWidth = 0;
            chart.ChartAreas[0].AxisY2.MajorGrid.LineWidth = 0;
            chart.ChartAreas[0].AxisY2.ScaleView.Zoomable = true;

            chart.ChartAreas[0].CursorX.AutoScroll = true;
            chart.ChartAreas[0].CursorX.IsUserEnabled = true;
            chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;

            chart.ChartAreas[0].CursorY.AutoScroll = true;
            chart.ChartAreas[0].CursorY.IsUserEnabled = true;
            chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = true;
        }
        public Guid SelectedStrategy
        {
            set
            {
                remoteGraphServer = new RemotingGraphServer("GraphServer",value);
                if (remoteGraphServer.GetGraph != null)
                {
                    remoteGraphServer.GetGraph.OnGraphRepaintHistory += GetGraphOnGraphRepaintHistory;
                    remoteGraphServer.GetGraph.OnGraphRepaint += GetGraphOnGraphRepaint;
                }
            }
        }
        private void ChartControl_Load(object sender, EventArgs e)
        {
            if (ParentForm != null)
            {
                ParentForm.Icon = Icon.FromHandle(Resources.Hors_ligne.GetHicon());
                ParentForm.SizeGripStyle = SizeGripStyle.Hide;
                ParentForm.MaximizeBox = true;
                ParentForm.MinimizeBox = true;
                ParentForm.StartPosition = FormStartPosition.CenterScreen;

                ParentForm.FormBorderStyle = FormBorderStyle.Sizable;
                ParentForm.ControlBox = true;
                ParentForm.Opacity = 0.9;
                Parent.Text = "Graph Server";
            }
        }
        private void GetGraphOnGraphRepaint(object sender, GraphEventArgs e)
        {
            if (IsHandleCreated)
            {
                var id = new Guid();
                if (e.DataToDraw is Trade)
                    id = ((Trade) e.DataToDraw).Id;
                else if(e.DataToDraw is Quote)
                    id = ((Quote)e.DataToDraw).Id;
                else if (e.DataToDraw is Bar)
                    id = ((Bar)e.DataToDraw).Id;

                if (TradeOrBarSeries.ContainsKey(id) && InvokeRequired)
                    chart.Invoke(pUpdateGraph, e);
                else if(InvokeRequired)
                    chart.Invoke(pAddGraph, e);
            }
        }
        private void GetGraphOnGraphRepaintHistory(object sender, GraphEventArgs e)
        {
            if (e.DataToDraw != null)
                chart.BeginInvoke(pAddGraphHystory, e);
        }
        private void AddGraphHystory(GraphEventArgs e)
        {
            if (chart.Series.Contains(HistoricalSerie))
                chart.Series.Remove(HistoricalSerie);

            var graphStyle = SeriesChartType.FastLine;
            if (e.DataToDraw is BarSeries)
                graphStyle = SeriesChartType.Stock;

            HistoricalSerie = new Series
                                  {
                                      ChartType = graphStyle,
                                      BorderWidth = 1,
                                      Color = Color.DarkGreen,
                                      XValueType = ChartValueType.DateTime,
                                      Name = e.ToString(),
                                      IsVisibleInLegend = false,
                                      Enabled = true
                                  };

            chart.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Auto; // Date + Time
            if (e.DataToDraw is TimeSeries)
            {
                var ts = (e.DataToDraw as TimeSeries);
                var minTime = ts.TimeSerie.FirstOrDefault().Key.ToOADate();
                var maxTime = ts.TimeSerie.LastOrDefault().Key.ToOADate();
                Parent.Text = string.Format("{0} - {1} elements - From :{2} To : {3}", HistoricalSerie.Name, ts.Count(), minTime, maxTime);

                foreach (var series in ts.TimeSerie)
                    HistoricalSerie.Points.Add(new DataPoint(series.Key.ToOADate(), (double)series.Value));
            }
            else if (e.DataToDraw is QuoteSeries)
            {
                var qs = (e.DataToDraw as QuoteSeries);
                Parent.Text = string.Format("{0} - {1} Quotes - From :{2} To : {3}", qs.Ticker, qs.Count, qs.FirstOrDefault().Time, qs.LastOrDefault().Time);

                foreach (Quote quote in qs)
                    HistoricalSerie.Points.Add(new DataPoint(quote.Time.ToOADate(), Decimal.ToDouble(quote.Mid)));
            }
            else if (e.DataToDraw is TradeSeries)
            {
                var t = (e.DataToDraw as TradeSeries);
                Parent.Text = string.Format("{0} - {1} Trades - From :{2} To : {3}", t.Ticker, t.Count, t.FirstOrDefault().Time, t.LastOrDefault().Time);

                foreach (Trade trade in t)
                    HistoricalSerie.Points.Add(new DataPoint(trade.Time.ToOADate(), Decimal.ToDouble(trade.Price)));
            }
            else if (e.DataToDraw is BarSeries)
            {
                var bs = (e.DataToDraw as BarSeries);
                Parent.Text = string.Format("{0} - {1} Duration: {2} - From :{3} To : {4}", bs.Ticker, bs.Count, bs.FirstOrDefault().Duration, bs.FirstOrDefault().BeginTime, bs.LastOrDefault().EndTime);

                foreach (Bar b in bs)
                {

                    HistoricalSerie.Points.Add(new DataPoint(b.BeginTime.ToOADate(), new[]
                                                                           {
                                                                               Decimal.ToDouble(b.High), 
                                                                               Decimal.ToDouble(b.Low), 
                                                                               Decimal.ToDouble(b.Open), 
                                                                               Decimal.ToDouble(b.Close)
                                                                           }));
                }
            }

            chart.Series[0].IsXValueIndexed = true;
            //chart.ChartAreas[0].AxisX.MajorGrid.Interval = 1;
            //chart.ChartAreas[0].AxisX.MajorTickMark.Interval = 1;
            //chart.ChartAreas[0].AxisX.LabelStyle.Interval = 1;
            chart.ChartAreas[0].AxisX.Interval = 40;
            chart.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Minutes;
            chart.ChartAreas[0].AxisX.IntervalOffset = 5;
            chart.ChartAreas[0].AxisX.IntervalOffsetType = DateTimeIntervalType.Minutes;

            chart.Series.Add(HistoricalSerie);
            chart.ResetAutoValues();
            chart.Invalidate(); 
        }
        private void AddGraph(GraphEventArgs u)
        {
            lock (this)
            {
                var Id = Guid.Empty;
                if (u.DataToDraw is Bar)
                    Id = ((Bar)u.DataToDraw).Id;
                else if (u.DataToDraw is Trade)
                    Id =((Trade)u.DataToDraw).Id;
                else if(u.DataToDraw is Quote)
                    Id = ((Quote)u.DataToDraw).Id;
                
                using (var db = new SystemathicsEntities(GlobalVariables.EntitiesConnectionString()))
                {
                    var query = db.DBInstruments.Where(z => z.ID == Id);
                    if (query.Any())
                    {
                        var dbi = query.FirstOrDefault();
                        Names.Add(Id, dbi.Name);
                        InstrumentsComboBox.Items.Add(dbi.Name);
                        dbi.DBExchangeReference.Load();

                        if (u.DataToDraw is Trade || u.DataToDraw is Quote)
                        {
                            TradeOrBarSeries[Id] = new Series
                                                       {
                                                           ChartType = SeriesChartType.FastLine, 
                                                           BorderWidth = 1, 
                                                           Color = Color.Black, 
                                                           XValueType = ChartValueType.Time, 
                                                           Name = dbi.Name
                                                       };
                        }
                        else if (u.DataToDraw is Bar)
                        {
                            TradeOrBarSeries[Id] = new Series
                                                       {
                                                           ChartType = SeriesChartType.Stock, 
                                                           BorderWidth = 1, 
                                                           Color = Color.Black, 
                                                           XValueType = ChartValueType.Time, 
                                                           Name = dbi.Name
                                                       };
                            TradeOrBarSeries[Id]["OpenCloseStyle"] = "Line";
                            TradeOrBarSeries[Id]["ShowOpenClose"] = "Both";
                            TradeOrBarSeries[Id]["BorderWidth "] = "2.0";
                        }

                        PLSeries[Id] = new Series
                                           {
                                               ChartType = SeriesChartType.FastLine, 
                                               BorderWidth = 1, 
                                               Color = Color.Green, 
                                               XValueType = ChartValueType.Time, 
                                               Name = "PL_" + dbi.Name
                                           };
                        PositionsSeries[Id] = new Series
                                                  {
                                                      ChartType = SeriesChartType.FastLine, 
                                                      BorderWidth = 1, 
                                                      Color = Color.Blue, 
                                                      XValueType = ChartValueType.Time, 
                                                      Name = "Pos_" + dbi.Name
                                                  };
                        if(u.CustomValue1Axis != null)
                        {
                            var ax = (u.CustomValue1Axis == FrameWork.Axis.Primary)
                                              ? AxisType.Primary
                                              : AxisType.Secondary;
                            CustomValuesSeries1[Id] = new Series
                                                      {
                                                          ChartType = SeriesChartType.FastLine,
                                                          BorderWidth = 1,
                                                          Color = Color.Blue,
                                                          XValueType = ChartValueType.Time,
                                                          XAxisType = AxisType.Primary,
                                                          YAxisType = ax, 
                                                          Name = "C1_" + dbi.Name
                                                      };
                            chart.Series.Add(CustomValuesSeries1[Id]);
                            CustomValuesSeries1[Id].IsVisibleInLegend = false;
                            if (u.CustomValue1 != 0)
                                CustomValuesSeries1[Id].Points.Add(new DataPoint(chart.ChartAreas[0].AxisX.Minimum, (double)u.CustomValue1));
                        }

                        if (u.CustomValue1Axis != null)
                        {
                            AxisType ax = (u.CustomValue2Axis == FrameWork.Axis.Primary)
                                              ? AxisType.Primary
                                              : AxisType.Secondary;

                            CustomValuesSeries2[Id] = new Series
                                                          {
                                                              ChartType = SeriesChartType.FastLine,
                                                              BorderWidth = 1,
                                                              Color = Color.Green,
                                                              XAxisType = AxisType.Primary,
                                                              XValueType = ChartValueType.Time,
                                                              YAxisType = ax,
                                                              Name = "C2_" + dbi.Name
                                                          };
                            chart.Series.Add(CustomValuesSeries2[Id]);
                            CustomValuesSeries2[Id].IsVisibleInLegend = false;
                            if (u.CustomValue2 != 0)
                                CustomValuesSeries2[Id].Points.Add(new DataPoint(chart.ChartAreas[0].AxisX.Minimum, (double)u.CustomValue2));
                        }

                        TradeOrBarSeries[Id].IsVisibleInLegend = false;
                        PLSeries[Id].IsVisibleInLegend = false;
                        PositionsSeries[Id].IsVisibleInLegend = false;

                        PLSeries[Id].Points.Add(new DataPoint(Time.Now.ToOADate(), 0));
                        PositionsSeries[Id].Points.Add(new DataPoint(Time.Now.ToOADate(), 0));

                        PLSeries[Id].Enabled = false;
                        PositionsSeries[Id].Enabled = false;

                        chart.Series.Add(TradeOrBarSeries[Id]);
                        chart.Series.Add(PLSeries[Id]);
                        chart.Series.Add(PositionsSeries[Id]);

                        chart.EndInit();

                        if (u.DataToDraw is Bar)
                        {
                            var bar = (Bar) u.DataToDraw;
                            chart.ChartAreas[0].AxisX.Minimum = bar.BeginTime.ToOADate();
                            TradeOrBarSeries[Id].Points.AddXY(bar.BeginTime.ToOADate(), bar.High);
                            TradeOrBarSeries[Id].Points[0].YValues[1] = Decimal.ToDouble(bar.Low);
                            TradeOrBarSeries[Id].Points[0].YValues[2] = Decimal.ToDouble(bar.Open);
                            TradeOrBarSeries[Id].Points[0].YValues[3] = Decimal.ToDouble(bar.Close);
                        }
                        else if(u.DataToDraw is Trade)
                        {
                            var tr = (Trade) u.DataToDraw;
                            chart.ChartAreas[0].AxisX.Minimum = tr.Time.ToOADate();
                            TradeOrBarSeries[Id].Points.Add(new DataPoint(tr.Time.ToOADate(), Decimal.ToDouble(tr.Price)));
                        }
                        else if(u.DataToDraw is Quote)
                        {
                            var q = (Quote) u.DataToDraw;
                            chart.ChartAreas[0].AxisX.Minimum = q.Time.ToOADate();
                            TradeOrBarSeries[Id].Points.Add(new DataPoint(q.Time.ToOADate(), Decimal.ToDouble(q.Mid)));
                        }

                        chart.ChartAreas[0].AxisX.Maximum = Time.Now.AddHours(AXIS_LENGTH).ToOADate();
                        chart.ResetAutoValues();
                        chart.Invalidate();
                    }
                }
            }
        }
        private void UpdateGraph(GraphEventArgs g)
        {
            double oleTime = 0;
            var currentDateTime = new DateTime();

            var id = new Guid();

            if (g.DataToDraw is Trade)
            {
                var t = (Trade)g.DataToDraw;
                id = t.Id;
                currentDateTime = t.Time;
                oleTime = t.Time.ToOADate();
                TradeOrBarSeries[id].Points.Add(new DataPoint(oleTime, Decimal.ToDouble(t.Price)));
            }
            else if (g.DataToDraw is Quote)
            {
                var q = (Quote)g.DataToDraw;
                id = q.Id;
                currentDateTime = q.Time;
                oleTime = q.Time.ToOADate();
                TradeOrBarSeries[id].Points.Add(new DataPoint(oleTime, Decimal.ToDouble(q.Mid)));
            }
            else if(g.DataToDraw is Bar)
            {
                var b = (Bar)g.DataToDraw;
                currentDateTime = b.BeginTime;
                oleTime = b.BeginTime.ToOADate();
                id = b.Id;
                TradeOrBarSeries[id].Points.Add(new DataPoint(oleTime, new[]
                                                                           {
                                                                               Decimal.ToDouble(b.High), 
                                                                               Decimal.ToDouble(b.Low), 
                                                                               Decimal.ToDouble(b.Open), 
                                                                               Decimal.ToDouble(b.Close)
                                                                           }));
            }

            PLSeries[id].Points.Add(new DataPoint(oleTime, g.Pl));
            PositionsSeries[id].Points.Add(new DataPoint(oleTime, g.Position));

            if (CustomValuesSeries1.ContainsKey(id) && g.CustomValue1 != 0)
                CustomValuesSeries1[id].Points.Add(new DataPoint(oleTime, (double)g.CustomValue1));
            if (CustomValuesSeries2.ContainsKey(id) && g.CustomValue2 != 0)
                CustomValuesSeries2[id].Points.Add(new DataPoint(oleTime, (double)g.CustomValue2));

            if (oleTime > chart.ChartAreas[0].AxisX.Maximum)
            {
                chart.ChartAreas[0].AxisX.Maximum = currentDateTime.AddHours(AXIS_LENGTH).ToOADate();
                chart.ResetAutoValues();
            }
            chart.Invalidate();
        }
        private void PriceToolStripButton_Click(object sender, EventArgs e)
        {
            if (SelectedGuid != Guid.Empty)
            {
                var id = SelectedGuid;
                TradeOrBarSeries[id].Enabled = true;
                if (CustomValuesSeries1.ContainsKey(id))
                    CustomValuesSeries1[id].Enabled = true;
                if (CustomValuesSeries2.ContainsKey(id))
                    CustomValuesSeries2[id].Enabled = true;
                PLSeries[id].Enabled = false;
                PositionsSeries[id].Enabled = false;

                chart.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.WhiteSmoke;
                chart.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.WhiteSmoke;

                // chart.ChartAreas[0].AxisY.CustomLabels.Add(0, MarketData.Open, "Open").ForeColor = Color.Black;
                // chart.ChartAreas[0].AxisY.CustomLabels.Add(0, MarketData.High, "High").ForeColor = Color.Red;
                // chart.ChartAreas[0].AxisY.CustomLabels.Add(0, MarketData.Low, "Low");
                // chart.ChartAreas[0].AxisY.CustomLabels.Add(0, MarketData.Close, "Close");

                // DataPoint min = TradeOrBarSeries[id].Points.FindMinByValue();
                // min.MarkerStyle = MarkerStyle.Diamond;
                // min.MarkerColor = Color.Red;
                // min.MarkerSize = 8;

                // DataPoint max = TradeOrBarSeries[id].Points.FindMaxByValue();
                // max.MarkerStyle = MarkerStyle.Diamond;
                // max.MarkerColor = Color.LightGreen;
                // max.MarkerSize = 8;
                chart.ResetAutoValues();
                chart.Invalidate();
            }
        }
        private void PLToolStripButton_Click(object sender, EventArgs e)
        {
            if (SelectedGuid != Guid.Empty)
            {
                Guid id = SelectedGuid;
                TradeOrBarSeries[id].Enabled = false;
                if (CustomValuesSeries1.ContainsKey(id))
                    CustomValuesSeries1[id].Enabled = false;
                if (CustomValuesSeries2.ContainsKey(id))
                    CustomValuesSeries2[id].Enabled = false;
                PLSeries[id].Enabled = true;
                PositionsSeries[id].Enabled = false;

                chart.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.LightGray;
                chart.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.LightGray;
                chart.ResetAutoValues();
                chart.Invalidate();
            }
        }
        private void PositionToolStripButton_Click(object sender, EventArgs e)
        {
            if (SelectedGuid != Guid.Empty)
            {
                var id = SelectedGuid;
                TradeOrBarSeries[id].Enabled = false;
                if (CustomValuesSeries1.ContainsKey(id))
                    CustomValuesSeries1[id].Enabled = false;
                if (CustomValuesSeries2.ContainsKey(id))
                    CustomValuesSeries2[id].Enabled = false;
                PLSeries[id].Enabled = false;
                PositionsSeries[id].Enabled = true;

                chart.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.LightGray;
                chart.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.LightGray;
                chart.ResetAutoValues();
                chart.Invalidate();
            }
        }
        private void InstrumentsComboBox_DropDownClosed(object sender, EventArgs e)
        {
            if (Names.Count > 0)
            {
                SelectedGuid = Names.Where(u => u.Value == InstrumentsComboBox.SelectedItem.ToString()).FirstOrDefault().Key;

                foreach (var id in Names.Keys)
                {
                    TradeOrBarSeries[id].Enabled = false;
                    PLSeries[id].Enabled = false;
                    PositionsSeries[id].Enabled = false;
                    if (CustomValuesSeries1.ContainsKey(id))
                        CustomValuesSeries1[id].Enabled = false;
                    if (CustomValuesSeries2.ContainsKey(id))
                        CustomValuesSeries2[id].Enabled = false;
                }

                TradeOrBarSeries[SelectedGuid].Enabled = true;
                if (CustomValuesSeries1.ContainsKey(SelectedGuid))
                    CustomValuesSeries1[SelectedGuid].Enabled = false;
                if (CustomValuesSeries2.ContainsKey(SelectedGuid))
                    CustomValuesSeries2[SelectedGuid].Enabled = true;
                chart.ResetAutoValues();
                chart.Invalidate();
            }
        }
        private void ExcelExporttoolStripButton_Click(object sender, EventArgs e)
        {
            if (SelectedGuid != Guid.Empty)
            {
                var dataSet = chart.DataManipulator.ExportSeriesValues(TradeOrBarSeries[SelectedGuid]);
                var fileName = Names[SelectedGuid] + "_" + DateTime.Now.ToFileTime() + "_Chart.xls";
                var oe = new ToExcel(fileName);
                oe.Add(dataSet);
                oe.Flush();
                oe.Close();
            }
            else if(HistoricalSerie.Points.Count > 0)
            {
                var dataSet = chart.DataManipulator.ExportSeriesValues(HistoricalSerie);
                var fileName = HistoricalSerie.Name + ".xls"; 
                var oe = new ToExcel(fileName);
                oe.Add(dataSet);
                oe.Flush();
                oe.Close();
            }
        }
        private void InstrumentsComboBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down)
            {
                var index = InstrumentsComboBox.SelectedIndex;
                if (InstrumentsComboBox.SelectedIndex < InstrumentsComboBox.Items.Count - 1)
                {
                    InstrumentsComboBox.SelectedItem = InstrumentsComboBox.Items[index];
                    InstrumentsComboBox_DropDownClosed(sender, e);
                }
            }
            else if (e.KeyCode == Keys.Up)
            {
                if (InstrumentsComboBox.SelectedIndex > 0)
                {
                    InstrumentsComboBox.SelectedItem = InstrumentsComboBox.Items[InstrumentsComboBox.SelectedIndex];
                    InstrumentsComboBox_DropDownClosed(sender, e);
                }
            }
        }
        private void ExtractDBSeriestoolStripButton_Click(object sender, EventArgs e)
        {
            new DataForm().ShowDialog();
        }
    }
}